/**
 * Created by Administrator on 2017/2/16 0016.
 */
$.select= function (selector) {
    return document.querySelectorAll(selector);
}
function $(selector){
    //构造函数为$.prototype.init
    return new $.prototype.init(selector);
}
$.fn=$.prototype={
    constructor:$,
    length:0,
    init: function (selector) {
        // 传入的如果是 0, '', nulll, undefined
        if ( !selector ) return this;
        Array.prototype.push.apply(this, $.select(selector));
    }
}
//构造函数的原型等于$的原型,两个公用一个原型,这样实例可以访问到$的原型里面的方法
$.fn.init.prototype= $.fn;
//添加增加方法的属性
$.extend= $.fn.extend= function (obj) {
    for(var k in obj){
        this[k]=obj[k];
    }
    return this;
}
//添加静态对象
$.extend({
    select:function (selector) {
        return document.querySelectorAll(selector);
    },
    isArrayLike: function (obj) {
       if( Object.prototype.toString.call(obj).slice(8,-1)=="Array"){
           return true;
       }
        var length='length' in obj && obj.length;
        return typeof length=='number'&&length>=0;
    },
    each: function (obj,callback) {
        if($.isArrayLike(obj)){
            for(var i=0;i<obj.length;i++){
              if(callback.call(obj[i],i,obj[i])==="false") break  ;
            }
        }else{
            for(var k in obj){
               if( callback.call(onj[k],k,obj[k])==="false") break;
            }
        }
    },
    map: function (obj, callback) {
        var arr=[],tmp;
        if($.isArrayLike(obj)){
            for(var i=0;i<obj.length;i++){
               tmp= callback(obj[i],i);
                if(tmp!=null){
                    arr.push(tmp)
                }
            }
        }else{
           tmp= callback(obj[k],k);
            if(tmp!=null){
                arr.push(tmp)
            }
        }
        return arr;
    }
})
//添加实例对象
$.fn.extend({
    map: function (callback) {
        return $.map(this,callback);
    },
    each: function (callback) {
        return $.each(this,callback);
    },
    toArray: function () {
      return  [].slice.call(this)
    },
    get: function (n) {
        if(n===undefined){
           return this.toArray()
        }
        if(n<0){
            return this[this.length+n];
        }else{
            return this[n];
        }
    },
    first: function () {
        var obj=this.constructor();
        [].push.call(obj,this.get(0));
        return obj;
    },
    last: function () {
        var obj=this.constructor();
        [].push.call(obj,this.get(-1));
        return obj;
    },
    eq: function (n) {
        if(n===undefined){
            return this.toArray()
        };
        var obj=this.constructor();
        [].push.call(obj,this.get(n))
        return obj;
    }
})